package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.Banner;
import com.itheima.domain.BannerExample;
import com.itheima.mapper.BannerMapper;
import com.itheima.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.ref.PhantomReference;
import java.util.ArrayList;
import java.util.List;

@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    // 查询轮播图
    @Override
    public List<Banner> findBannerList() {
        List<Banner> list = null;
        // 1.先查缓存
        if (redisTemplate.hasKey("banner_list")) {
            list = (List<Banner>) redisTemplate.opsForValue().get("banner_list");
            System.err.println("查询缓存");
        } else {
            // 2.再查数据库，并同步
            PageHelper.startPage(1, 5);
            BannerExample bannerExample = new BannerExample();
            bannerExample.setOrderByClause("order_no desc");
            list = bannerMapper.selectByExample(bannerExample);
            // 同步到缓存
            redisTemplate.opsForValue().set("banner_list", list);
            System.err.println("查询MySQL");
        }

        return list;
    }
}
